import request from '@/utils/request.js'
import { Message } from 'element-ui'

export function exportFile(url, data, filename, params = { method: 'post' }) {
  return new Promise((resolve, reject) => {
    request({
      url: url,
      data: data,
      timeout: 600000,
      responseType: 'blob', // 指定获取数据的类型为blob
      ...params
    })
      .then(function (response) {
        if (response.type === 'application/json') {
          console.log(response)
          const reader = new FileReader()
          reader.readAsText(response)
          reader.onload = function () {
            const msg = JSON.parse(reader.result) // 此处的msg就是后端返回的msg内容
            if (msg.code === '-500') {
              Message({
                message: msg.result,
                type: 'error',
                duration: 3 * 1000
              })
            }
            if (msg.code === '-1') {
              Message({
                message: '系统错误!',
                type: 'error',
                duration: 3 * 1000
              })
            }
            resolve(msg)
          }
        } else {
          // console.log('response:' + response)
          // 创建a标签并点击， 即触发下载
          const url = window.URL.createObjectURL(response)
          const link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', filename)
          document.body.appendChild(link)
          link.click()
          URL.revokeObjectURL(link.href) // 释放URL 对象
          document.body.removeChild(link)
          resolve()
        }
      })
      .catch(function () {
        reject()
      })
  })
}
